using System.Collections.Generic;
using System.Reflection;
using Core.Runtime;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace Hotfix.Runtime
{
    public class GameEntry
    {
        public static List<Assembly> HotFixAssemblies = new();

        /// <summary>
        /// 热更域App主入口。
        /// </summary>
        /// <param name="objects"></param>
        public static async UniTaskVoid Entrance(object[] objects)
        {
            Debug.Log("热更域App主入口");
            var hotfixAssemblies = objects as Assembly[];
            InitHotFixAssemblies(hotfixAssemblies);
            await InitHotFixSystem();
            await GameStart();
        }

        public static void Exit()
        {
            PersistentObjects.ReleaseAll();
        }

        private static void InitHotFixAssemblies(Assembly[] objects)
        {
            Debug.Log("初始化热更域程序集");
            HotFixAssemblies.Clear();
            HotFixAssemblies.AddRange(objects);
        }

        private static async UniTask InitHotFixSystem()
        {
            Debug.Log("初始化热更域系统");
            await InitEventSystem();
            await InitUnityLifecycleRegistrySystem();
            await InitGameObjectPoolSystem();
            await InitUISystem();
        }


        private static async UniTask InitEventSystem()
        {
            await UniTask.Yield();
            PersistentObjects.AddPersistentObject<EventLifecycle>(priority: 100);
            Debug.Log("初始化Event 生命周期");
        }

        private static async UniTask InitGameObjectPoolSystem()
        {
            await UniTask.Yield();
            PersistentObjects.AddPersistentObject<GameObjectPoolLifecycle>();
            GameObjectPoolManager.Root = PersistentObjects.GetPersistentObject<GameObjectPoolLifecycle>().transform;
            Debug.Log("初始化GameObjectPool 生命周期");
        }

        /// <summary>
        /// Unity生命周期管理
        /// </summary>
        private static async UniTask InitUnityLifecycleRegistrySystem()
        {
            await UniTask.Yield();
            PersistentObjects.AddPersistentObject<UnityLifecycleRegistry>();
            Debug.Log("初始化Unity 生命周期注册");
        }

        private static async UniTask InitUISystem()
        {
            await UniTask.Yield();
            var uiRootPath = "Assets/AssetPacks/Prefabs/System/UIRoot.prefab";
            var uiRoot = await AssetManager.InstantiateAsync(uiRootPath);
            uiRoot.name = uiRoot.name.Replace("(Clone)", string.Empty);
            PersistentObjects.AddPersistentObject<UIManager>(uiRoot);
        }

        private static async UniTask GameStart()
        {
            Debug.Log("游戏开始");
            await AssetManager.LoadSceneAsync("Assets/AssetPacks/Scenes/GameStart.unity");
            await SceneManager.UnloadSceneAsync("Launcher");
        }
    }
}